package sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-15
 * Time: 16:29
 */
public class heapSort {
    public static void main(String[] args) {
        int[] arr = {2, 1, 32, 1, 32, 1, 32, 1, 3};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void heapSort(int[] arr) {
        //向下调整为大根堆
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            shiftDown(arr, i, arr.length);
        }
        for (int i = arr.length - 1; i >= 0; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            shiftDown(arr, 0,i);
        }
    }
    public static void shiftDown(int[] arr, int parent, int size) {
        int child = 2 * parent + 1;
        while (child < size) {
            if (child + 1 < size && arr[child + 1] > arr[child]) {
                child++;
            }
            if (arr[child] > arr[parent]) {
                int temp = arr[child];
                arr[child] = arr[parent];
                arr[parent] = temp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }
}
